import React, { Component } from 'react';
import { Col, Row, Icon, Label, FormControl, Select } from 'tinper-bee';
import DatePicker from 'bee-datepicker';
import './index.less';
import GirdRefer from './GridRefer/index.jsx'
import TreeRefer from './TreeRefer/index.jsx'
import CustomerReferContainer from './CustomerReferContainer/index.jsx';
import AllCustomerReferContainer from './AllCustomerReferContainer/index.jsx';
import RangePicker from '../RangePicker/index.jsx'
import { vendorsFmtDate } from 'utils/config.js';
class YgcForm extends Component {
    constructor(props) {
        super(props);
        let formData = {};
        this.props.items.forEach(cur => {
            formData[cur.attrcode] = {};
            if (typeof cur.defaultValue === 'function') {
                formData[cur.attrcode] = cur.defaultValue();
            } else if (cur.defaultValue) {
                formData[cur.attrcode] = cur.defaultValue;
            }
        })
        this.state = {
            gridReferConfig: {
            },
            treeReferConfig: {
            },
            customReferConfig: {

            },
            allcustomReferConfig: {

            },
            formData,
            operationDisplay: props.operationDisplay || false,
        }
        this.output = {
            collectFormValue: this.collectFormValue,
            setFormValue: this.setFormValue,
            setFormStatus: this.setFormStatus,
            getFormStatus: this.getFormStatus,
            getFormItemValue: this.getFormItemValue,
            setFormItemValue: this.setFormItemValue,
            setFormItemsValue: this.setFormItemsValue,
            clearFormValue: this.clearFormValue,
            validateForm: this.validateForm,
        }

    }
    setFormStatus = (status) => {
        this.setState({
            status
        })
    }
    getFormStatus = () => {
        return this.state.status;
    }
    validateForm = () => {
        let errorItems = [];
        let formData = this.state.formData;
        this.props.items.forEach(cur => {
            if (cur.required) {
                if (!formData[cur.attrcode].value && formData[cur.attrcode].value !== 0) {
                    errorItems.push(cur.label);
                    formData[cur.attrcode].hasError = true;
                } else {
                    formData[cur.attrcode].hasError = false;
                }
            }
        })
        this.setState({
            formData
        })
        return errorItems;
    }
    getFormItemValue = (attrcode) => {
        return this.state.formData[attrcode];
    }
    setFormItemValue = (attrcode, value) => {
        this.setItemValue(attrcode, value);
    }
    setFormItemsValue = (values) => {
        this.setState((state) => {
            let formData = Object.assign(state.formData, values);
            return {
                formData,
            }
        })
    }

    setItemValue = (attrcode, value) => {
        let oldvalue = this.state.formData[attrcode];
        this.setState((state) => {
            state.formData[attrcode] = value;
            return {
                formData: state.formData,
            }
        }, () => {
            if (typeof this.props.afterEvent == 'function') {
                this.props.afterEvent(attrcode, oldvalue, value);
            }
        })
    }
    showRefer = (refType, referConfig) => {
        referConfig.isShow = true;
        if (refType == 'grid') {
            referConfig.columns.forEach(cur => {
                cur.dataIndex = cur.key;
            })
            this.setState({
                gridReferConfig: referConfig,
            })
        } else if (refType == 'tree') {
            this.setState({
                treeReferConfig: referConfig,
            })
        } else if (refType == 'custom') {
            this.setState({
                customReferConfig: referConfig,
            })
        } else if (refType == 'allcustom') {
            this.setState({
                allcustomReferConfig: referConfig,
            })
        }
    }
    closeRefer = () => {
        this.setState((state) => {
            state.gridReferConfig.isShow = false;
            state.treeReferConfig.isShow = false;
            state.customReferConfig.isShow = false;
            state.allcustomReferConfig.isShow = false;
            return {
                gridReferConfig: state.gridReferConfig,
                treeReferConfig: state.treeReferConfig,
                customReferConfig: state.customReferConfig,
                allcustomReferConfig: state.allcustomReferConfig,
            }
        })
    }
    getSelected = (attrcode, value) => {
        this.setItemValue(attrcode, value);
    }
    clearItemSeleted = (attrcode) => {
        this.setItemValue(attrcode, { display: '', value: '' });
    }
    collectFormValue = () => {
        let data = {};
        for (let key in this.state.formData) {
            data[key] = this.state.formData[key].value;
        }
        return data;
    }
    setFormValue = (data, dataDisplay) => {
        let formData = {};
        this.props.items.forEach(cur => {
            formData[cur.attrcode] = {};
        })
        for (let key in data) {
            formData[key] = { value: data[key] };
        }
        for (let key in dataDisplay) {
            formData[key].display = dataDisplay[key];
        }
        this.setState({
            formData
        })
    }
    clearFormValue = (data) => {
        let formData = {};
        this.props.items.forEach(cur => {
            formData[cur.attrcode] = {};
            if (typeof cur.defaultValue === 'function') {
                formData[cur.attrcode] = cur.defaultValue();
            } else if (cur.defaultValue) {
                formData[cur.attrcode] = cur.defaultValue;
            }
        })
        this.setState({
            formData,
            // status: 'edit'
        })
    }
    toggleOperationInfoDisplay = () => {
        this.setState(state => {
            return {
                operationDisplay: !state.operationDisplay,
            }
        })
    }
    renderItem = (cur) => {
        let itemData = this.state.formData[cur.attrcode] || {};
        return (<YgcFormItem
            {...cur}
            value={itemData.value}
            display={itemData.display}
            hasError={itemData.hasError}
            status={this.state.status}
            setItemValue={this.setItemValue}
            showRefer={this.showRefer}
            clearItemSeleted={this.clearItemSeleted}
        />)
    }
    render() {
        let {
            items,
            hasOperationInfo = false,
            operationItems = [
                {
                    attrcode: 'creatorname',
                    label: '制单人',
                    disabled: true,
                    placeholder: '',
                },
                {
                    attrcode: 'creationtime',
                    label: '制单日期',
                    disabled: true,
                    placeholder: '',
                },
                // {
                //     attrcode: 'modifier',
                //     label: '最后修改人',
                //     disabled: true,
                //     placeholder: '',
                // },
                // {
                //     attrcode: 'modifytime',
                //     label: '最后修改时间',
                //     disabled: true,
                //     placeholder: '',
                // },
            ],
        } = this.props;
        let {
            gridReferConfig,
            treeReferConfig,
            customReferConfig,
            allcustomReferConfig,
            formData,
            status,
            operationDisplay,
        } = this.state;
        return (
            <div className='ygc-form-container'>
                <Row>
                    {
                        items.map(cur => this.renderItem(cur))
                    }
                </Row>
                {
                    hasOperationInfo &&
                    <Row>
                        <div className="operation-container">
                            <div className="operator" onClick={this.toggleOperationInfoDisplay}>
                                <span className="name" tabindex="0">
                                    <span className="name-icon">{operationDisplay ? '-' : '+'}</span>操作信息</span>
                                <span className="line-wrap">
                                    <span className="line">
                                    </span>
                                </span>
                            </div>
                        </div>
                    </Row>
                }
                {
                    hasOperationInfo && operationDisplay &&
                    <Row>
                        {
                            operationItems.map(cur => this.renderItem(cur))
                        }
                    </Row>
                }

                <GirdRefer
                    {...gridReferConfig}
                    closeRefer={this.closeRefer}
                    getSelected={this.getSelected}
                />
                <TreeRefer
                    {...treeReferConfig}
                    closeRefer={this.closeRefer}
                    getSelected={this.getSelected}
                />
                <CustomerReferContainer
                    {...customReferConfig}
                    closeRefer={this.closeRefer}
                    getSelected={this.getSelected}
                />
                <AllCustomerReferContainer
                    {...allcustomReferConfig}
                    closeRefer={this.closeRefer}
                    getSelected={this.getSelected}
                />
            </div>
        )
    }
}

export default YgcForm;



class YgcFormItem extends Component {
    super(props) {

    }

    setItemValue = (e) => {
        this.props.setItemValue(this.props.attrcode, { value: e.target.value });
    }

    clearItemSeleted = () => {
        this.props.clearItemSeleted(this.props.attrcode);
    }
    showRefer = () => {
        let {
            attrcode,
            disabled,
            label,
            reqRef = {},
            refType,
            showRefer,
            value,
        } = this.props;
        if (disabled) return;
        showRefer(refType, {
            attrcode,
            label,
            selected: value,
            ...reqRef
        });
    }
    onSectionDateChange = (timeArr) => {
        let startTime = vendorsFmtDate(timeArr[0]);
        let endTime = vendorsFmtDate(timeArr[1]);
        this.props.setItemValue(this.props.attrcode, { value: { startTime, endTime } });
    };
    onDateChange = (date) => {
        this.props.setItemValue(this.props.attrcode, { value: date });
    }
    onSelectChange = (value) => {
        let {
            attrcode,
            selectOptions = [],
            setItemValue,
        } = this.props;
        setItemValue(attrcode, { value, display: selectOptions.find(cur => cur.value == value).label });
    }
    render() {
        let {
            attrcode,
            clearDisabled = false,
            col = 3,
            disabled = false,
            display = '',
            hasError = false,
            isnextrow = false,
            itemtype = 'input',
            label,
            placeholder,
            refType,
            reqRef = {},
            required = false,
            selectOptions = [],
            setItemValue,
            showRefer,
            status,
            value = '',
            visible = true,
            visibleEdit = true,
            visibleBrowse = true,
        } = this.props;
        if (!visible) {
            return null;
        }
        if (status == 'browse') {
            if (!visibleBrowse) {
                return null;
            }
            let content = null;
            switch (itemtype) {
                case 'refer':
                case 'select':
                    content = display;
                    break;
                case 'section-date':
                    content = value && `${value.startTime}~${value.endTime}`;
                    break;
                case 'date':
                    content = value && (value.format ? value.format('YYYY-MM-DD') : value);
                    break;
                case 'textarea':
                    content = <div className='textarea'>
                        {value}
                    </div>;
                    break;
                default:
                    content = value;
                    break;
            }
            return (
                <Col className={isnextrow ? 'col-next-row' : ''} md={col} sm={col * 2} xs={col * 4}>
                    <div className="form-panel-item">
                        <div className='form-panel-item-label'>
                            {label}
                            <span className="form-item-colon"> ：</span>
                        </div>

                        < div className='form-panel-item-browse'
                            title={itemtype == 'textarea' ? value : content}>
                            {content}
                        </div>
                    </div>
                </Col>
            )
        } else {
            if (!visibleEdit) {
                return null;
            }
            let content = null;
            let emptyIcon = !clearDisabled && value && !disabled && <Icon className='item-empty-icon' type="uf-close-c" onClick={this.clearItemSeleted} />;
            switch (itemtype) {
                case 'input':
                    content = <FormControl
                        placeholder={isEmpty(placeholder) ? `请输入${label}` : placeholder}
                        disabled={disabled}
                        value={value}
                        onChange={this.setItemValue}
                    />
                    break;
                case 'refer':
                    content = <div>
                        <FormControl
                            className={`ref-input`}
                            placeholder={placeholder || `请选择${label}`}
                            disabled={disabled}
                            value={display}
                        />
                        <Icon type='uf-navmenu'
                            className='form-panel-item-input-icon'
                            onClick={this.showRefer}
                        />
                        {emptyIcon}
                    </div>
                    break;
                case 'section-date':
                    content = <div >
                        <RangePicker
                            disabled={disabled}
                            className='form-panel-item-input-datapicker'
                            startTime={value.startTime}
                            endTime={value.endTime}
                            onChange={this.onSectionDateChange}
                        />
                        {emptyIcon}
                    </div>
                    break;
                case 'date':
                    content = <div >
                        <DatePicker
                            format={'YYYY-MM-DD'}
                            value={value}
                            onChange={this.onDateChange}
                            disabled={disabled}
                            showClose={false}
                            showDateInput={!clearDisabled}
                            placeholder={placeholder || `请选择日期`}
                            className={"form-panel-item-input-datapicker"}
                        />
                        {emptyIcon}
                    </div>
                    break;
                case 'select':
                    content = <div>
                        <Select
                            // defaultValue="all"
                            // style={{ width: 200, marginRight: 6 }}
                            onChange={this.onSelectChange}
                            showSearch={true}
                            allowClear={true}
                            placeholder={placeholder}
                            defaultValue={value}
                            filterOption={(input, option) => {
                                if (option.key && option.key.includes(input)) {
                                    return true;
                                } else {
                                    return false;
                                }
                            }}
                        >
                            {
                                selectOptions.map(cur => {
                                    return <Option key={cur.label} value={cur.value}>{cur.label}</Option>
                                })
                            }
                        </Select>
                    </div>
                    break;
                case 'textarea':
                    col = 12;
                    content = <div className='form-input-textarea-container'>
                        <FormControl
                            className={'form-input-textarea'}
                            placeholder={placeholder || `请输入${label}`}
                            disabled={disabled}
                            value={value}
                            onChange={this.setItemValue}
                            componentClass='textarea'
                        />
                    </div>
                default:
                    break;
            }
            return (
                <Col className={isnextrow ? 'col-next-row' : ''} md={col} sm={col * 2} xs={col * 4}>
                    <div className="form-panel-item">
                        <div className='form-panel-item-label'>
                            {required ? <span className='form-panel-item-required'>*</span> : null}
                            {label}
                        </div>

                        < div className={`form-panel-item-control ${hasError ? 'error-border' : ''}`}>
                            {content}
                        </div>
                        <span className='error'>

                        </span>
                    </div>
                </Col>
            )
        }
    }
}

function isEmpty(value) {
    if (value === null || value === undefined) {
        return true;
    } else {
        return false;
    }
}